using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class BoneAnimationRecorder : MonoBehaviour
{
    public Animator animator;
    private string saveFilePath = "Assets/BoneAnimations.json";
    
    void Start()
    {
        SaveBoneTransforms();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            LoadAndApplyBoneTransforms();
        }
    }

    void SaveBoneTransforms()
    {
        List<BoneTransformData> boneTransforms = new List<BoneTransformData>();

        foreach (HumanBodyBones bone in System.Enum.GetValues(typeof(HumanBodyBones)))
        {
            if (bone != HumanBodyBones.LastBone)
            {
                Transform boneTransform = animator.GetBoneTransform(bone);
                if (boneTransform != null)
                {
                    boneTransforms.Add(new BoneTransformData()
                    {
                        BoneName = bone.ToString(),
                        Position = boneTransform.localPosition,
                        Rotation = boneTransform.localRotation
                    });
                }
            }
        }

        string json = JsonUtility.ToJson(new BoneTransformDataCollection { BoneData = boneTransforms });
        File.WriteAllText(saveFilePath, json);
    }

    void LoadAndApplyBoneTransforms()
    {
        string json = File.ReadAllText(saveFilePath);
        BoneTransformDataCollection boneDataCollection = JsonUtility.FromJson<BoneTransformDataCollection>(json);

        foreach (BoneTransformData boneData in boneDataCollection.BoneData)
        {
            HumanBodyBones bone;
            if (System.Enum.TryParse(boneData.BoneName, out bone))
            {
                Transform boneTransform = animator.GetBoneTransform(bone);
                if (boneTransform != null)
                {
                    boneTransform.localPosition = boneData.Position;
                    boneTransform.localRotation = boneData.Rotation;
                }
            }
        }
    }
}

[System.Serializable]
public class BoneTransformData
{
    public string BoneName;
    public Vector3 Position;
    public Quaternion Rotation;
}

[System.Serializable]
public class BoneTransformDataCollection
{
    public List<BoneTransformData> BoneData;
}
